package cn.iocoder.yudao.module.engine.service.boot;

import cn.hutool.core.util.IdUtil;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.module.engine.model.aichat.AIChatReq;
import cn.iocoder.yudao.module.engine.service.core.aichat.IAIChatService;
import cn.iocoder.yudao.module.engine.service.core.aichat.client.impl.BotILLMChatClient;
import cn.iocoder.yudao.module.infra.util.TraceIdUtil;
import cn.iocoder.yudao.module.resource.api.IAudioToneApi;
import cn.iocoder.yudao.module.resource.api.ICosplayApi;
import cn.iocoder.yudao.module.resource.api.ISessionApi;
import cn.iocoder.yudao.module.resource.api.model.AudioToneDTO;
import cn.iocoder.yudao.module.resource.api.model.CosplayDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.telegram.telegrambots.client.okhttp.OkHttpTelegramClient;
import org.telegram.telegrambots.longpolling.BotSession;
import org.telegram.telegrambots.longpolling.interfaces.LongPollingUpdateConsumer;
import org.telegram.telegrambots.longpolling.starter.AfterBotRegistration;
import org.telegram.telegrambots.longpolling.starter.SpringLongPollingBot;
import org.telegram.telegrambots.longpolling.util.LongPollingSingleThreadUpdateConsumer;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.User;
import org.telegram.telegrambots.meta.generics.TelegramClient;

import java.time.Instant;

@Slf4j
public class TelChatBot implements SpringLongPollingBot, LongPollingSingleThreadUpdateConsumer {
    private final String botToken = "7871746207:AAHAtAGGnOfgRi-6LjwVP9oslj0zje5ssiE";
    private final TelegramClient telegramClient = new OkHttpTelegramClient(botToken);

    @Resource
    private IAIChatService chatService;
    @Resource
    private ISessionApi sessionApi;
    @Resource
    private ICosplayApi cosplayApi;
    @Resource
    private IAudioToneApi audioToneApi;

    @AfterBotRegistration
    public void afterRegistration(BotSession botSession) {
        log.info("注册ChatBoot: " + botSession.isRunning());
    }

    @Override
    public void consume(Update update) {
        try {
            TraceIdUtil.setTraceId(IdUtil.objectId());
            final boolean hasText = update.hasMessage() && update.getMessage().hasText();
            log.info("收到ChatBoot消息, hasMessage = {}, hasText = {}, update = {}",
                    update.hasMessage(), hasText, JsonUtils.toJsonString(update));
            if (hasText) {
                final User from = update.getMessage().getFrom();
                final Long chatId = update.getMessage().getChatId();
                final String type = update.getMessage().getChat().getType();
                final Integer messageId = update.getMessage().getMessageId();
                final String textFromUser = update.getMessage().getText();
                log.info("收到ChatBoot消息, userId = {}, type = {}, chatId = {}, messageId = {}, text = {}",
                        from.getId(), type, chatId, messageId, textFromUser);

                final Long loginUserId = from.getId();
                final Integer roleId = 4;
                final Long sessionId = sessionApi.getSessionByRoleIdWithLock(loginUserId, Long.valueOf(roleId), null);

                final CosplayDTO role = cosplayApi.getCosplay(roleId);
                final AudioToneDTO tone = audioToneApi.getById(Integer.parseInt(role.getAudioToneId()));

                final BotILLMChatClient chatClient = new BotILLMChatClient(telegramClient, update);
                final AIChatReq req = AIChatReq.builder()
                        .chatId(IdUtil.objectId())
                        .chatClient(chatClient)
                        .websocketStart(Instant.now())
                        .userId(loginUserId)
                        .gameMatchId(null)
                        .wsSessionId(sessionId.toString())
                        .role(role)
                        .tone(tone)
                        .userText(textFromUser)
                        .historyMessages(null)
                        .build();
                chatService.createMessage(req);
            }
        } catch (Exception e) {
            log.warn("处理ChatBoot消息失败", e);
            TraceIdUtil.removeTraceId();
        }
    }

    @Override
    public String getBotToken() {
        return botToken;
    }

    @Override
    public LongPollingUpdateConsumer getUpdatesConsumer() {
        return this;
    }
}
